package com.waimai.utils;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.waimai.log.Log;

public class HtmlParserUtils {

	/**
	 * 
	 * @param bytes
	 *            需要查询的html转化byte[]字节码
	 * @param charset
	 *            解码类型
	 * @param filter
	 *            遍历过滤器 详细看这个
	 *            http://blog.csdn.net/code52/article/details/6293862
	 * @return 节点列表
	 * @throws ParserException
	 */
	public static NodeList getNodeListByBytes(byte[] bytes, String charset,
			NodeFilter filter) {
		NodeList l = new NodeList();
		if (bytes != null) {
			String str = new String(bytes);
			Parser parser = Parser.createParser(str, charset);
			try {
				l = parser.extractAllNodesThatMatch(filter);
			} catch (ParserException e) {
				// TODO Auto-generated catch block
				Log.e(e, "getNodeListByBytes error");
				e.printStackTrace();
			}
		}
		return l;
	}

	/**
	 * 匹配一组子节点
	 * 
	 * @param n
	 *            父节点
	 * @param filter
	 *            过滤器 http://blog.csdn.net/code52/article/details/6293862
	 * 
	 * @return 节点列表
	 */
	public static NodeList getChildrenNodeList(Node n, NodeFilter filter) {
		NodeList l = new NodeList();
		// 遍历所有下面的节点，将符合的返回到列表中
		n.collectInto(l, filter);
		return l;
	}

	/**
	 * 只匹配一个子节点
	 * 
	 * @param n
	 *            父节点
	 * @param filter
	 *            过滤器 http://blog.csdn.net/code52/article/details/6293862
	 * 
	 * @return 节点
	 */
	public static Node getChildNode(Node n, NodeFilter filter) {
		Node node = null;
		try {
			node = getChildrenNodeList(n, filter).elementAt(0);
		} catch (NullPointerException e) {
			Log.e(e, "has no childNode");
			e.printStackTrace();

		}
		return node;
	}
}
